package org.example.springboot3.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.springboot3.entity.Employee;
import org.example.springboot3.service.EmployeeService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.Date;

@Component
public class TokenUtils {
    @Resource
    EmployeeService employeeService;
    static EmployeeService staticEmployeeService;
    @PostConstruct
    public void init() {
        staticEmployeeService = employeeService;
    }
    /**
     * 生成token
     */
    public static String createToken(String data, String sign) {
        return JWT.create().withAudience(data) // 将 username-role 保存到 token 里面,作为载荷
                .withExpiresAt(DateUtil.offsetDay(new Date(), 1)) // 1天后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥，HMAC256算法加密
    }
//
public static Employee getCurrentUser() {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    String token = request.getHeader("token");
    if (StrUtil.isBlank(token)) {
        token = request.getParameter("token");
    }
    String audience = JWT.decode(token).getAudience().get(0);
    String[] split = audience.split("-");
    String username = split[0];
    String role = split[1];
    //4
    if ("adm".equals(role)) {
        return  staticEmployeeService.selectByUsername(username);
    } else if ("EMP".equals(role)) {
      return  staticEmployeeService.selectByUsername(username);
    }
    return null;
}

}
